import axios from "@/utils/requestdp";
import uuidv1 from "uuid/v1";
import dayjs from "dayjs";

let zz = {
  watch: {
    "$store.state.daping.scencetype": {
      handler: function(n, o) {
        if (this.catchdata) {
          this.loaddatabytype();
        }
      }
      // immediate: true,
    },

    // catchdata: {
    //   handler: function(n, o) {
    //     if (this.catchdata) {
    //       this.loaddatabytype();
    //     }
    //   }
    // }
  },

  data() {
    return {
      catchdata: false
    };
  },
  methods: {
    zhengzhou() {
      this.$store.state.daping.threecom = this;
      this.$store.state.daping.scencetype = "gongre";
      // this.$store.state.daping.scencetype = "nengxiao";
      //初始化数据操作
      this.catchtydata();
      //全局pick事件
      this.initother();
    },

    initother() {
      let _this = this;
      let viewer = this.viewer;
      //添加点击事件
      viewer.screenSpaceEventHandler.setInputAction(function onLeftClick(
        movement
      ) {
        var pickedFeature = viewer.scene.pick(movement.position);

        if (typeof pickedFeature != "undefined") {
          console.log(pickedFeature);
          if (pickedFeature.id.properties != undefined) {
            _this.pickleftclick({
              id: pickedFeature.id.id,
              pid: pickedFeature.id.id.split(".")[1],
              position: Cesium.Cartographic.fromCartesian(
                pickedFeature.id.position._value
              )
            });
          } else {
            _this.pickleftclick({
              id: pickedFeature.id.name.split(".")[0],
              pid: pickedFeature.id.name.split(".")[1],
              position: Cesium.Cartographic.fromCartesian(
                pickedFeature.id.position._value
              )
            });
          }
        }
      },
      Cesium.ScreenSpaceEventType.LEFT_CLICK);
    },

    pickleftclick(options) {
      switch (this.$store.state.daping.scencetype) {
        case "gongre":
          this.gongrepick(options);
          break;
        case "nengxiao":
          this.gongrepick(options);
          break;
        default:
          break;
      }
    },

    loaddatabytype() {
      //清空数据
      this.destoryds();
      //添加能效图缓存
      // this.catchnengxiaozzn();
      //加载数据
      switch (this.$store.state.daping.scencetype) {
        case "nengxiao":
          this.nengxiao();
          break;
        case "gongre":
          this.gongre();
          break;
        default:
          break;
      }
    },

    catchnengxiaodata(paramsstr) {
      //能效图数据信息
      //查询条件
      let queryJson = {
        queries: [
          {
            metric: "pid,name," + paramsstr,
            schema: "monitor",
            table: "substation"
          }
        ],
        type: "lastest",
        prefix: "manage",
        foundColumn: "heating_area",
        needMap: true
      };

      console.log(queryJson);

      let reqquerydb = axios.post("/open/queryDb", queryJson);
      reqquerydb.then(res => {
        let efficiencydata = res.data;
        Object.keys(efficiencydata).map(key => {
          let tmp_003 = 0;
          let danhao = efficiencydata[key][0]["m_003qc"];
          let mianji = efficiencydata[key][0]["heating_area"];
          tmp_003 = Number(
            Number(((Number(danhao) / 3.6) * 1000000) / Number(mianji)).toFixed(
              0
            )
          );
          if (isNaN(tmp_003) || tmp_003 == Infinity) {
            tmp_003 = 0;
          }
          if (tmp_003 > 200) {
            tmp_003 = 200;
          }
          efficiencydata[key][0]["m_003qc"] = tmp_003;
        });
        this.$root.efficiency_data["efficiencydata"] = efficiencydata;
      });
    },

    catchtydata() {
      let _this = this;
      this.catchdata = false;

      //loaddata

      //geojson模型数据
      //能效图接口数据
      //
      /**
       * 1. model/model模型数据     effical/模型数据
       * 2. 接口数据缓存
       * 3. 数据缓存完成之后调用对应方法
       *
       */

      //获取所有数据，二个接口
      // //能效图单位配置信息+++++++++++++
      // let reqhm = axios.get("/heatmap/queryConfig11");
      
      //modelcolor 接口(停运站，区块颜色.........)
      let reqmc = axios.get("/model/modelColor4BigScreen?type=region");
      
      //接口缓存数据版本
      let requ = axios.get("/model/queryModelIdAndWorkingId");
      
      // 获取管径
      // /model/pipeline/dn
      // let reqdn = axios.get("/model/pipeline/dn");
      
      let params = [reqmc, requ]
      
      console.log(this.$root.threesetting.gisnx);
      
      if (this.$root.threesetting.gisnx && this.$root.threesetting.gisnx == 'gisnx') {
        let reqhm = axios.get("/heatmap/queryConfig");
        params.push(reqhm)
      }

      //发送请求
      Promise.all(params).then(res => {
        //判断返回值
        //----------------------能效图接口相关--------------------
        if (this.$root.threesetting.gisnx && this.$root.threesetting.gisnx == 'gisnx') {
          let config_data = res[2].data;
          //缓存能效图接口数据
          this.catchnengxiaodata(Object.keys(config_data).join(","));
  
          //全局配置信息存储
          this.$root.efficiency_data = {
            // efficiencydata: efficiencydata,
            config_data: config_data
          };
          this.$store.state.daping.efficiency.config_data = config_data;
        }

        _this.mc = res[0].data;
        
        if (!_.has(_this.mc,"stop")) {
          _this.mc['stop'] = []
        }

        if (!_.has(_this.mc,"outSource")) {
          _this.mc['outSource'] = []
        }

        if (!_.has(_this.mc,"heatplant")) {
          _this.mc['heatplant'] = []
        }

        // if (!_.has(_this.mc,"stop")) {
        //   _this.mc['stop'] = []
        // }
        _this.dn = {};
        // res[3].data.map(item => {
        //   _this.dn[item.dn] = item.dnvalue
        // })

        //判断本地缓存和modelcolor 接口|缓存
        //----------------------------判断本地缓存和modelcolor 接口---------------
        let updatemsg = res[1].data;
        //根据id判断加载在线还是缓存数据
        //获取indexdb    管网和区域信息
        let modelid = localStorage.getItem("modelId")
        console.log(modelid);
        console.log(updatemsg.modelId);
        if (modelid != updatemsg.modelId || modelid == null) {
          this.getModel(updatemsg.modelId, () => {
            //判断是否有缓存有的话就加载没有的话就发请求获取
            // this.catchdata = true;
            this.loadenter()

          });
        }else{
          // this.catchdata = true;
          this.loadenter()

        }
      });
    },

    async getModel(id, callback) {
      let proName = this.$store.state.daping.type;
      const IDB_DATA = {
        dbName: "daping",
        dbVersion: 15,
        tableName: proName + "mapModel",
        modelKey: "gisModal",
        modelKey1: "nengxiaoModal"
      };
      let db = null;
      const request = window.indexedDB.open(
        IDB_DATA.dbName,
        IDB_DATA.dbVersion
      );
      const getModalData = (db, event, type) => {
        // if (type != 'error') {

        if (this.$root.threesetting.gisnx && this.$root.threesetting.gisnx == 'gisnx') {
          let reqgis = axios.get("/model/model");
          let reqnx = axios.get("/model/efficiency");
  
          Promise.all([reqgis, reqnx]).then(res => {
            if (res[0].code == 200) {
              localStorage.setItem("modelId",res[0].data.modelId)
              const modalData = JSON.stringify(res[0].data);
              const modalDatanx = JSON.stringify(res[1]);
              // 写入indexedDB
              // console.log(modalData)
              const objectStore = db
                .transaction(IDB_DATA.tableName, "readwrite")
                .objectStore(IDB_DATA.tableName);
              const requestClear = objectStore.clear();
              requestClear.onsuccess = function(event) {
                console.log("清空成功");
              };
              requestClear.onerror = function(event) {
                console.log("清空失败");
              };
  
              const requestAdd = objectStore.add({
                id: IDB_DATA.modelKey,
                data: modalData
              });
              requestAdd.onsuccess = function(event) {
                console.log("写入成功");
              };
              requestAdd.onerror = function(event) {
                console.log("写入失败");
              };
  
              const requestAddnx = objectStore.add({
                id: IDB_DATA.modelKey1,
                data: modalDatanx
              });
              requestAddnx.onsuccess = function(event) {
                console.log("写入成功");
              };
              requestAddnx.onerror = function(event) {
                console.log("写入失败");
              };
            }
            callback();
          });
          
        }else{
          let reqgis = axios.get("/model/model");
          Promise.all([reqgis]).then(res => {
            if (res[0].code == 200) {
              localStorage.setItem("modelId",res[0].data.modelId)
              const modalData = JSON.stringify(res[0].data);
              // 写入indexedDB
              // console.log(modalData)
              const objectStore = db
                .transaction(IDB_DATA.tableName, "readwrite")
                .objectStore(IDB_DATA.tableName);
              const requestClear = objectStore.clear();
              requestClear.onsuccess = function(event) {
                console.log("清空成功");
              };
              requestClear.onerror = function(event) {
                console.log("清空失败");
              };
  
              const requestAdd = objectStore.add({
                id: IDB_DATA.modelKey,
                data: modalData
              });
              requestAdd.onsuccess = function(event) {
                console.log("写入成功");
              };
              requestAdd.onerror = function(event) {
                console.log("写入失败");
              };
  
            }
            callback();
          });

        }




      };
      request.onerror = event => {
        console.log("数据库打开失败");
        return getModalData(db, event, "error");
      };
      request.onsuccess = event => {
        db = event.target.result;
        console.log("数据库打开成功");
        this.$message.success("加载在线接口数据")
        getModalData(db, event, "reload");
      
      };
      request.onupgradeneeded = event => {
        db = event.target.result;
        console.log("onupgradeneeded");

        if (!db.objectStoreNames.contains(IDB_DATA.tableName)) {
          const objectStore = db.createObjectStore(IDB_DATA.tableName, {
            keyPath: "id"
          });
        }
      };
    },

    async getModelval(type, callback) {
      let proName = this.$store.state.daping.type;
      const IDB_DATA = {
        dbName: "daping",
        dbVersion: 15,
        tableName: proName + "mapModel",
        modelKey: "gisModal",
        modelKey1: "nengxiaoModal"
      };
      let db = null;
      const request = window.indexedDB.open(
        IDB_DATA.dbName,
        IDB_DATA.dbVersion
      );

      request.onerror = event => {
        console.log("数据库打开失败");
      };
      request.onsuccess = event => {
        db = event.target.result;
        console.log("数据库打开成功");

        const requestRead = db
          .transaction(IDB_DATA.tableName)
          .objectStore(IDB_DATA.tableName)
          .get(type);
        requestRead.onerror = function(event) {
          console.log("读取失败");
        };
        requestRead.onsuccess = event => {
          console.log("读取成功", event);
          const result = event.target.result;
          callback(result.data);
        };
      };
      request.onupgradeneeded = event => {
        db = event.target.result;
        console.log("onupgradeneeded");

        if (!db.objectStoreNames.contains(IDB_DATA.tableName)) {
          const objectStore = db.createObjectStore(IDB_DATA.tableName, {
            keyPath: "id"
          });
        }
      };
    },

    catchnengxiaozzn() {
      console.log("fsdfsdfsdfsdfsdf");
      let _this = this;
      //查询条件
      // let queryJson = {
      //   queries: [
      //     {
      //       metric:
      //         "pid,name,m_019t_1,m_003p,m_001p,m_001t,m_002t,m_002t,m_004t_1,m_003qc",
      //       schema: "monitor"
      //     }
      //   ],
      //   table: "SubStation",
      //   needMap: true
      // };

      let queryJson = {
        queries: [
          {
            metric:
              "pid,name,m_019t_1,m_003p,m_001p,m_001t,m_002t,m_002t,m_004t_1,m_003qc",
            schema: "monitor",
            table: "substation"
          }
        ],
        type: "lastest",
        prefix: "manage",
        foundColumn: "heating_area",
        needMap: true
      };
      //获取所有数据，三个接口
      let reqqueryconfig = axios.get("/heatmap/queryConfig");
      // let reqstations = axios.post(
      //   "/model/stations?from=daping&needMap=true",
      //   {}
      // );
      let reqquerydb = axios.post("/open/queryDb", queryJson);
      //发送请求
      Promise.all([reqqueryconfig, reqquerydb]).then(res => {
        // Promise.all([reqqueryconfig,reqstations,reqquerydb]).then(res =>{
        //格式化单耗值
        // let g_areaData = res[1].data;
        let efficiencydata = res[1].data;

        Object.keys(efficiencydata).map(key => {
          let tmp_003 = 0;
          let danhao = efficiencydata[key]["m_003qc"];
          let mianji = efficiencydata[key]["heating_area"];

          tmp_003 = Number(
            Number(((Number(danhao) / 3.6) * 1000000) / Number(mianji)).toFixed(
              0
            )
          );

          if (isNaN(tmp_003) || tmp_003 == Infinity) {
            tmp_003 = 0;
          }

          if (tmp_003 > 200) {
            tmp_003 = 200;
          }

          efficiencydata[key]["m_003qc"] = tmp_003;
        });

        this.$root.efficiency_data = {
          efficiencydata: efficiencydata,
          config_data: res[0].data
        };
      });
    },

    destoryds() {
      //清理geojson数据     能效供热
      if (this.ds.length != 0) {
        for (let index1 = 0; index1 < this.ds.length; index1++) {
          for (
            let index = 0;
            index < this._viewer.dataSources.length;
            index++
          ) {
            if (this.ds[index1] == this._viewer.dataSources.get(index)._name) {
              this._viewer.dataSources.remove(
                this._viewer.dataSources.get(index)
              );
            }
          }
        }
      }

      //清理odlines
      _.forIn(this.odlinesarr, (v, k) => {
        v.destroy();
      });

      //清理EarthSDK点
      let pinarr = this.pinarr;
      pinarr.map(item => {
        this._earth.sceneTree.root.children.map((eactpin, index) => {
          if (eactpin.ref == item) {
            this._earth.sceneTree.root.children.splice(index, 1);
          }
        });
      });
      //清理3d卡片
      let _this = this;
      _.forIn(this.dependlistArr, function(value, key) {
        _this.dependlistArr[key] = [];
      });
      //清理数据源
      this.ds = [];
    }
  }
};

export default zz;
